﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebStore.Domain.Entities;
using WebStore.Domain.Entities.Enum;
using WebStore.Domain.Entities.Model;
using WebStore.Web.App.Utility.Enum;
using WebStore.Web.App.Utility.Other;

namespace WebStore.Web.App.Controllers
{
    public class BaseController : Controller
    {
        protected readonly Entities _entities;

        public BaseController(Entities entities)
        {
            _entities = entities;
            ViewBag.IsInRole = new Func<RoleType, bool>(IsInRole);
        }

        private User _currentUser;
        public User CurrentUser
        {
            get
            {
                return _currentUser ??
                       (_currentUser = _entities.Users.FirstOrDefault(x => x.Email == HttpContext.User.Identity.Name));
            }
        }
        private const string ClientMessageKey = "ClientMessage";
        protected void CreateMessage(string message, ClientMessageType messageType)
        {
            if (TempData[ClientMessageKey] == null)
                TempData[ClientMessageKey] = new List<ClientMessage>();
            ((List<ClientMessage>)TempData[ClientMessageKey]).Add(new ClientMessage { Message = message, ClientMessageType = messageType });
        }


        private bool IsInRole(RoleType role)
        {
            return CurrentUser != null && CurrentUser.UserRoles.Any(x => x.Role.RoleType == role);
        }
    }
}